<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function indexDeal(orderedArr, target) {
        //两个函数是防止递归时数据初始化，将初始化放在子函数外
        let left = 0;
        let right = orderedArr.length - 1;
        let min = Math.round((left + right) / 2);
        dicSearch(orderedArr, target, min, left, right);
        function dicSearch(orderedArr, target, min, left, right) {
          if (orderedArr[min] !== target) {
            if (orderedArr[min] < target) {
              //先将等与不等划分，在判断大小
              left = min + 1;
              if (left > right) {
                //当左索引大于右索引时说明没有目标
                console.log("未找到");
                return 1;
              } else {
                min = Math.round((left + right) / 2);
                console.log(min);
                dicSearch(orderedArr, target, min, left, right); //递归
              }
            } else {
              right = min - 1;
              if (left > right) {
                //当左索引大于右索引时说明没有目标
                console.log("未找到");
                return 1;
              } else {
                min = Math.round((left + right) / 2);
                console.log(min);
                dicSearch(orderedArr, target, min, left, right);
              }
            }
          } else {
            console.log(min);
            return 1;
          }
        }
      }
      indexDeal([1, 2, 3, 4, 6, 7, 7, 8, 9, 15, 17, 27], 16);
    </script>
  </body>
</html>
